package org.example.model;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.*;
import org.apache.poi.xwpf.usermodel.*;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import static org.example.domain.ListTable.*;
import org.example.mapper.JsonTest;


public class WordTemplateReplace {
    public static void replace(String file, String data) {
        try {
            FileInputStream fis = new FileInputStream(file);
            XWPFDocument document = new XWPFDocument(fis);
            for (XWPFParagraph paragraph : document.getParagraphs()) {
                String text = paragraph.getText();
                Pattern pattern1 = Pattern.compile("<var\\s+name=(\\w+)\\s+ds=(.*?)\\s+query=(.*?)>");
                Matcher matcher1 = pattern1.matcher(text);
                Pattern pattern2 = Pattern.compile("<out\\s+var=(\\w+)>");
                Matcher matcher2 = pattern2.matcher(text);
                Pattern pattern3 = Pattern.compile("<foreach>");
                Matcher matcher3 = pattern3.matcher(text);
                Pattern pattern4 = Pattern.compile("<out\\s+var=(\\w+)\\s+foreach>");
                Pattern pattern11 = Pattern.compile("<out\\s+var=(\\w+) max>");
                Matcher matcher11 = pattern11.matcher(text);
                Pattern pattern12 = Pattern.compile("<out\\s+var=(\\w+) min>");
                Matcher matcher12 = pattern12.matcher(text);
                Pattern pattern13 = Pattern.compile("<out\\s+var=(\\w+) count>");
                Matcher matcher13 = pattern13.matcher(text);
                Pattern pattern14 = Pattern.compile("<out\\s+var=(\\w+) sum>");
                Matcher matcher14 = pattern14.matcher(text);
                Pattern pattern15 = Pattern.compile("<out\\s+var=(\\w+) avg>");
                Matcher matcher15 = pattern15.matcher(text);

                List<String> tablename=new ArrayList<>();


                if (matcher1.find()) {
                    String name = matcher1.group(1); // 获取第一个括号中匹配的内容，即 name
                    String ds = matcher1.group(2);   // 获取第二个括号中匹配的内容，即 ds
                    String query = matcher1.group(3); // 获取第三个括号中匹配的内容，即 query
                    varlist.add(name);
                    datasourcelist.add(ds);
                    querylist.add(query);
                    Object a= JsonTest.Jsonreplace(data,query);
                    hashTable.put(name,a);
                    typetable.put(name,gettype.gettype(a));
                    System.out.println("Name: " + name);
                    System.out.println("DS: " + ds);
                    System.out.println("Query: " + query);
                    text=text.replaceAll("<var\\s+name=(\\w+)\\s+ds=(.*?)\\s+query=(.*?)>","");
                    List<XWPFRun> runs=paragraph.getRuns();
                    for(int i=0;i<runs.size();i++){
                        XWPFRun run =runs.get(i);
                        run.setText("",0);
                    }
                    paragraph.removeRun(0);
                    XWPFRun newrun=paragraph.createRun();
                    newrun.setText(text);

                }
                if(matcher2.find()){
                    String name = matcher2.group(1);
                    if (varlist.contains(name)){
                        text = text.replaceAll("<out\\s+var=(\\w+)>",hashTable.get(name).toString());
                        System.out.println("有" + text);
                    }
                    List<XWPFRun> runs=paragraph.getRuns();
                    for(int i=0;i<runs.size();i++){
                        XWPFRun run =runs.get(i);
                        run.setText("",0);
                    }

                    paragraph.removeRun(0);
                    XWPFRun newrun=paragraph.createRun();
                    newrun.setText(text);
                }
                if(matcher11.find()){
                    String name = matcher11.group(1);
                    if (varlist.contains(name)) {
                        if (typetable.get(name).equals("listdouble")) {
                            List<Double>list=(List<Double>) hashTable.get(name);
                            double max = -100000; // 初始化

                            for (Double number:list) {
                                if (number > max) {
                                    max = number;
                                }
                            }

                            text = text.replaceAll("<out\\s+var=(\\w+) max>", max+"");
                            System.out.println("有" + text);
                        }
                        if (typetable.get(name).equals("listint")) {
                            List<Integer>list=(List<Integer>) hashTable.get(name);
                            int max = -100000; // 初始化为可能的最小值

                            for (Integer number:list) {
                                if (number < max) {
                                    max = number;
                                }
                            }

                            text = text.replaceAll("<out\\s+var=(\\w+) max>", max+"");
                            System.out.println("有" + text);
                        }
                    }
                    List<XWPFRun> runs=paragraph.getRuns();
                    for(int i=0;i<runs.size();i++){
                        XWPFRun run =runs.get(i);
                        run.setText("",0);
                    }

                    paragraph.removeRun(0);
                    XWPFRun newrun=paragraph.createRun();
                    newrun.setText(text);
                }
                if(matcher12.find()){
                    String name = matcher12.group(1);
                    if (varlist.contains(name)) {
                        if (typetable.get(name).equals("listdouble")) {
                            List<Double>list=(List<Double>) hashTable.get(name);
                            double min = 100000; // 初始化为可能的最小值

                            for (Double number:list) {
                                if (number < min) {
                                    min = number;
                                }
                            }

                            text = text.replaceAll("<out\\s+var=(\\w+) min>", min+"");
                            System.out.println("有" + text);
                        }
                        if (typetable.get(name).equals("listint")) {
                            List<Integer>list=(List<Integer>) hashTable.get(name);
                            int min = 100000; // 初始化为可能的最小值

                            for (Integer number:list) {
                                if (number < min) {
                                    min = number;
                                }
                            }

                            text = text.replaceAll("<out\\s+var=(\\w+) min>", min+"");
                            System.out.println("有" + text);
                        }
                    }
                    List<XWPFRun> runs=paragraph.getRuns();
                    for(int i=0;i<runs.size();i++){
                        XWPFRun run =runs.get(i);
                        run.setText("",0);
                    }

                    paragraph.removeRun(0);
                    XWPFRun newrun=paragraph.createRun();
                    newrun.setText(text);
                }
                if(matcher13.find()){
                    String name = matcher13.group(1);
                    if (varlist.contains(name)) {
                        List<?>list=(List<?>) hashTable.get(name);
                        Set<?> set = new HashSet<>(list);
                        text = text.replaceAll("<out\\s+var=(\\w+) count>", set.size()+"");

                    }
                    List<XWPFRun> runs=paragraph.getRuns();
                    for(int i=0;i<runs.size();i++){
                        XWPFRun run =runs.get(i);
                        run.setText("",0);
                    }

                    paragraph.removeRun(0);
                    XWPFRun newrun=paragraph.createRun();
                    newrun.setText(text);


                }
                if(matcher14.find()){
                    String name = matcher14.group(1);
                    if (varlist.contains(name)) {
                        if (typetable.get(name).equals("listdouble")) {
                            List<Double>list=(List<Double>) hashTable.get(name);
                            double sum = 0;

                            for (Double number:list) {
                                sum+=number;
                            }

                            text = text.replaceAll("<out\\s+var=(\\w+) sum>", sum+"");
                            System.out.println("有" + text);
                        }
                        if (typetable.get(name).equals("listint")) {
                            List<Integer>list=(List<Integer>) hashTable.get(name);
                            int sum=0;
                            for (Integer number:list) {
                                sum+=number;
                            }

                            text = text.replaceAll("<out\\s+var=(\\w+) sum>", sum+"");
                            System.out.println("有" + text);
                        }
                    }
                    List<XWPFRun> runs=paragraph.getRuns();
                    for(int i=0;i<runs.size();i++){
                        XWPFRun run =runs.get(i);
                        run.setText("",0);
                    }

                    paragraph.removeRun(0);
                    XWPFRun newrun=paragraph.createRun();
                    newrun.setText(text);
                }
                if(matcher15.find()){
                    String name = matcher15.group(1);
                    if (varlist.contains(name)) {
                        if (typetable.get(name).equals("listdouble")) {
                            List<Double>list=(List<Double>) hashTable.get(name);
                            double avg = 0; // 初始化为可能的最小值

                            for (Double number:list) {
                                avg+=number;
                            }

                            text = text.replaceAll("<out\\s+var=(\\w+) avg>", avg/list.size()+"");
                            System.out.println("有" + text);
                        }
                        if (typetable.get(name).equals("listint")) {
                            List<Integer>list=(List<Integer>) hashTable.get(name);
                            int avg=0; // 初始化为可能的最小值

                            for (Integer number:list) {
                                avg+=number;
                            }

                            text = text.replaceAll("<out\\s+var=(\\w+) sum>", avg/list.size()+"");
                            System.out.println("有" + text);
                        }
                    }
                    List<XWPFRun> runs=paragraph.getRuns();
                    for(int i=0;i<runs.size();i++){
                        XWPFRun run =runs.get(i);
                        run.setText("",0);
                    }

                    paragraph.removeRun(0);
                    XWPFRun newrun=paragraph.createRun();
                    newrun.setText(text);
                }


                if(matcher3.find()){
                    for (XWPFTable table : document.getTables()) {
                        for (int i = 0; i < table.getNumberOfRows(); i++) {
                            for (int j = 0; j < table.getRow(i).getTableCells().size(); j++) {
                                // 获取单元格中的所有段落
                                for (XWPFParagraph paragraph1 : table.getRow(i).getCell(j).getParagraphs()) {
                                    for (XWPFRun run : paragraph1.getRuns()) {
                                        // 检查是否包含文本"a"
                                        Matcher m4= pattern4.matcher(run.text());
                                        if (m4.find()) {
                                            String name= m4.group(1);
                                            tablename.add(name);
                                            System.out.println(name+"Found at row " + i + ", column " + j);
                                            int[]temp={i,j};
                                            tablenameindex.put(name,temp);
                                        }
                                    }
                                }
                            }
                        }
                    }
                }
                int[]a=new int[tablename.size()];
                int num=0;

                for(String str:tablename){


                    if(gettype.gettype(hashTable.get(str)).equals("liststring")){
                        List<String>list=(List<String>) hashTable.get(str);
                        a[index]=list.size();
                        num=a[0];
                        indexlist.put(str,list);
                        index++;

                    }
                    if(gettype.gettype(hashTable.get(str)).equals("listdouble")){
                        List<Double>list=(List<Double>) hashTable.get(str);
                        a[index]=list.size();
                        List<String> strings = new ArrayList<String>();
                        for (Double d : list) {
                            strings.add(d.toString());
                        }
                        indexlist.put(str,strings);//double 转string
                        index++;

                    }
                    if(gettype.gettype(hashTable.get(str)).equals("listint")){
                        List<Integer>list=(List<Integer>) hashTable.get(str);
                        a[index]=list.size();
                        List<String> strings = new ArrayList<String>();
                        for (Integer d : list) {
                            strings.add(d.toString());
                        }
                        indexlist.put(str,strings);

                        index++;

                    }

                }
                boolean flag=true;

                for(int j=1;j< tablename.size();j++){
                    if(a[j]!=a[0]){
                        System.out.println("不匹配");
                        flag=false;

                    }

                }


                if(flag==true){
                    for(int j=0;j<num;j++){
                        XWPFTable originalTable = document.getTables().get(0);
                        XWPFTable newTable = document.createTable(0,0);

                        for (XWPFTableRow row : originalTable.getRows()) {
                            XWPFTableRow newRow = newTable.createRow();
                            newRow.setHeight(200);


                            for (XWPFTableCell cell : row.getTableCells()) {
                                XWPFTableCell newCell = newRow.createCell();
                                TableWidthType type=cell.getWidthType();
                                newCell.setWidthType(type);


                                for (XWPFParagraph paragraph1 : cell.getParagraphs()) {
                                    XWPFParagraph newParagraph = newCell.addParagraph();
                                    for (XWPFRun run : paragraph1.getRuns()) {
                                        XWPFRun newRun = newParagraph.createRun();
                                        newRun.setText(run.getText(0));
                                    }
                                }
                            }
                        }


                    for(int x=0;x< tablename.size();x++){
                        newTable.getRow(tablenameindex.get(tablename.get(x))[0]+1).getCell(tablenameindex.get(tablename.get(x))[1]+1).removeParagraph(0);

                        newTable.getRow(tablenameindex.get(tablename.get(x))[0]+1).getCell(tablenameindex.get(tablename.get(x))[1]+1).setText(indexlist.get(tablename.get(x)).get(j));
                        System.out.println(indexlist.get(tablename.get(x)).get(j));

                    }
                        for (XWPFTableRow row : newTable.getRows()) {
                            // 移除每行的第一列
                            row.removeCell(0);
                        }
                    }
                }

            }
            for (XWPFTable table : document.getTables()) {
                for (XWPFTableRow row : table.getRows()) {
                    for (int i = 0; i < row.getTableCells().size(); i++) {
                        String text = row.getCell(i).getText();
                        Pattern pattern2 = Pattern.compile("<out\\s+var=(\\w+)>");
                        Matcher matcher2 = pattern2.matcher(text);
                        Pattern pattern11 = Pattern.compile("<out\\s+var=(\\w+) max>");
                        Matcher matcher11 = pattern11.matcher(text);
                        Pattern pattern12 = Pattern.compile("<out\\s+var=(\\w+) min>");
                        Matcher matcher12 = pattern12.matcher(text);
                        Pattern pattern13 = Pattern.compile("<out\\s+var=(\\w+) count>");
                        Matcher matcher13 = pattern13.matcher(text);
                        Pattern pattern14 = Pattern.compile("<out\\s+var=(\\w+) sum>");
                        Matcher matcher14 = pattern14.matcher(text);
                        Pattern pattern15 = Pattern.compile("<out\\s+var=(\\w+) avg>");
                        Matcher matcher15 = pattern15.matcher(text);
                        if (matcher2.find()) {
                            String name = matcher2.group(1);
                            if (varlist.contains(name)){
                                text = text.replaceAll("<out\\s+var=(\\w+)>",hashTable.get(name).toString());
                                System.out.println("表格中有" + text);
                            }
                            row.getCell(i).removeParagraph(0);

                            row.getCell(i).setText(text);
                        }
                        if(matcher11.find()){
                            String name = matcher11.group(1);
                            if (varlist.contains(name)) {
                                if (typetable.get(name).equals("listdouble")) {
                                    List<Double>list=(List<Double>) hashTable.get(name);
                                    double max = -100000; // 初始化

                                    for (Double number:list) {
                                        if (number > max) {
                                            max = number;
                                        }
                                    }

                                    text = text.replaceAll("<out\\s+var=(\\w+) max>", max+"");
                                    System.out.println("有" + text);
                                }
                                if (typetable.get(name).equals("listint")) {
                                    List<Integer>list=(List<Integer>) hashTable.get(name);
                                    int max = -100000; // 初始化为可能的最小值

                                    for (Integer number:list) {
                                        if (number < max) {
                                            max = number;
                                        }
                                    }

                                    text = text.replaceAll("<out\\s+var=(\\w+) max>", max+"");
                                    System.out.println("有" + text);
                                }
                            }
                            row.getCell(i).removeParagraph(0);

                            row.getCell(i).setText(text);
                        }
                        if(matcher12.find()){
                            String name = matcher12.group(1);
                            if (varlist.contains(name)) {
                                if (typetable.get(name).equals("listdouble")) {
                                    List<Double>list=(List<Double>) hashTable.get(name);
                                    double min = 100000; // 初始化为可能的最小值

                                    for (Double number:list) {
                                        if (number < min) {
                                            min = number;
                                        }
                                    }

                                    text = text.replaceAll("<out\\s+var=(\\w+) min>", min+"");
                                    System.out.println("有" + text);
                                }
                                if (typetable.get(name).equals("listint")) {
                                    List<Integer>list=(List<Integer>) hashTable.get(name);
                                    int min = 100000; // 初始化为可能的最小值

                                    for (Integer number:list) {
                                        if (number < min) {
                                            min = number;
                                        }
                                    }

                                    text = text.replaceAll("<out\\s+var=(\\w+) min>", min+"");
                                    System.out.println("有" + text);
                                }
                            }
                            row.getCell(i).removeParagraph(0);

                            row.getCell(i).setText(text);
                        }
                        if(matcher13.find()){
                            String name = matcher13.group(1);
                            if (varlist.contains(name)) {
                                List<?>list=(List<?>) hashTable.get(name);
                                Set<?> set = new HashSet<>(list);
                                text = text.replaceAll("<out\\s+var=(\\w+) count>", set.size()+"");

                            }
                            row.getCell(i).removeParagraph(0);

                            row.getCell(i).setText(text);


                        }
                        if(matcher14.find()){
                            String name = matcher14.group(1);
                            if (varlist.contains(name)) {
                                if (typetable.get(name).equals("listdouble")) {
                                    List<Double>list=(List<Double>) hashTable.get(name);
                                    double sum = 0; // 初始化为可能的最小值

                                    for (Double number:list) {
                                        sum+=number;
                                    }

                                    text = text.replaceAll("<out\\s+var=(\\w+) sum>", sum+"");
                                    System.out.println("有" + text);
                                }
                                if (typetable.get(name).equals("listint")) {
                                    List<Integer>list=(List<Integer>) hashTable.get(name);
                                    int sum=0; // 初始化为可能的最小值

                                    for (Integer number:list) {
                                        sum+=number;
                                    }

                                    text = text.replaceAll("<out\\s+var=(\\w+) sum>", sum+"");
                                    System.out.println("有" + text);
                                }
                            }
                            row.getCell(i).removeParagraph(0);

                            row.getCell(i).setText(text);
                        }
                        if(matcher15.find()){
                            String name = matcher15.group(1);
                            if (varlist.contains(name)) {
                                if (typetable.get(name).equals("listdouble")) {
                                    List<Double>list=(List<Double>) hashTable.get(name);
                                    double avg = 0; // 初始化为可能的最小值

                                    for (Double number:list) {
                                        avg+=number;
                                    }

                                    text = text.replaceAll("<out\\s+var=(\\w+) avg>", avg/list.size()+"");
                                    System.out.println("有" + text);
                                }
                                if (typetable.get(name).equals("listint")) {
                                    List<Integer>list=(List<Integer>) hashTable.get(name);
                                    int avg=0; // 初始化为可能的最小值

                                    for (Integer number:list) {
                                        avg+=number;
                                    }

                                    text = text.replaceAll("<out\\s+var=(\\w+) sum>", avg/list.size()+"");
                                    System.out.println("有" + text);
                                }
                            }
                            row.getCell(i).removeParagraph(0);

                            row.getCell(i).setText(text);
                        }


                    }
                }
            }
            List<TableCell> cellsToExpand = new ArrayList<>();
            for (XWPFTable table : document.getTables()) {
                for (XWPFTableRow row : table.getRows()) {
                    for (XWPFTableCell cell : row.getTableCells()) {
                        // 检查单元格中的段落是否包含"<out var=a expand>"
                        for (XWPFParagraph paragraph : cell.getParagraphs()) {
                            String text = paragraph.getText();
                            Pattern patternExpand = Pattern.compile("\\<out\\s+var=(\\w+)\\s+expand\\>");
                            Matcher matcherExpand = patternExpand.matcher(text);
                            if (matcherExpand.find()) {
                                String varName = matcherExpand.group(1);
                                if (hashTable.containsKey(varName)) {
                                    // 记录需要扩展的单元格
                                    cellsToExpand.add(new TableCell(table, row, cell,varName));
                                }
                            }
                        }
                    }
                }
            }

            // 根据记录的位置信息，进行单元格的扩展
            for (TableCell cellToExpand : cellsToExpand) {
                XWPFTableCell cell = cellToExpand.getCell();
                TableWidthType type=cell.getWidthType();
                XWPFTableRow row = cellToExpand.getRow();
                String varName = cellToExpand.getVarName();
                int j=cell.getWidth();

                Object varValue = hashTable.get(varName);
                if (varValue instanceof List) {
                    List<?> list = (List<?>) varValue;

                    for (int i = 0; i < list.size(); i++) {
                        XWPFTableCell newCell = row.createCell();
                        newCell.setWidth(String.valueOf(j));
                        newCell.setText(list.get(i).toString());
                    }
                }
            }

            FileOutputStream out=new FileOutputStream("output.docx");
            document.write(out);
            document.close();
            fis.close();
            for(String str:typetable.keySet()){
                System.out.print(typetable.get(str)+"|");
            }

        } catch (FileNotFoundException e) {
            throw new RuntimeException(e);
        } catch (IOException e) {
            throw new RuntimeException(e);
        }

    }
    private static class TableCell {
        private final XWPFTable table;
        private final XWPFTableRow row;
        private final XWPFTableCell cell;
        private final String varName;

        public TableCell(XWPFTable table, XWPFTableRow row, XWPFTableCell cell,String varName) {
            this.table = table;
            this.row = row;
            this.cell = cell;
            // 这里需要根据实际情况获取变量名
            this.varName = varName;
        }

        public XWPFTable getTable() {
            return table;
        }

        public XWPFTableRow getRow() {
            return row;
        }

        public XWPFTableCell getCell() {
            return cell;
        }

        public String getVarName() {
            return varName;
        }
    }


}